﻿using System;
using System.Linq;
using UnityEngine;

//Call -> AudioManager.Instance.[FunctionName]
[Serializable]
public class Sound
{
    public string Name;
    public bool IsLooping;
    public AudioClip Clip;

    [Range(0f, 1f)]
    public float Volume;

    private AudioSource source;

    public void SetSource(AudioSource s)
    {
        source = s;
        source.clip = Clip;
        s.playOnAwake = false;
    }

    public void Play(float masterVolume)
    {
        if (GameFlowManager.Instance.CheckIfGameIsFinished())
            return;
        source.volume = Volume * masterVolume;
        source.loop = IsLooping;
        source.Play();
    }

    public void Stop()
    {
        source.Stop();
    }
}

public class AudioManager : Singleton<AudioManager>
{
    [SerializeField]
    public Sound[] Sounds;

    [Range(0f, 1f)]
    public float MasterVolume = 1f;

    [SerializeField]
    private bool _debugMode;

    private void Start()
    {
        for (int i = 0; i < Sounds.Length; i++)
        {
            var obj = new GameObject($"Sound_{i}_{Sounds[i].Name}");
            obj.transform.SetParent(transform);
            Sounds[i].SetSource(obj.AddComponent<AudioSource>());
        }
    }

    public void PlaySound(string name)
    {
        Sounds.FirstOrDefault(s => s.Name == name)?.Play(MasterVolume);
    }

    public void StopSound(string name)
    {
        Sounds.FirstOrDefault(s => s.Name == name)?.Stop();
    }

    private void OnGUI()
    {
        if (!_debugMode) return;

        if (GUILayout.Button("Load All AudioClips"))
        {
            var audioClips = Resources.LoadAll<AudioClip>("Audio");
            Sounds = new Sound[audioClips.Length];
            for (var i = 0; i < audioClips.Length; i++)
            {
                Sounds[i] = new Sound {Name = audioClips[i].name, IsLooping = false, Clip = audioClips[i], Volume = 1f};
            }
        }

        if (GUILayout.Button("Test Audio"))
        {
            Sounds[0].Play(MasterVolume);
        }
    }
}